import express from 'express'
import globalCache from '../../../cache.js'
import { getAccount, hasLogin } from '../../../middleWare/user/index.js'
var router = express.Router()
import {getResult,listSql, addSql, putSql, detailSql, deleteSql} from '../../../util/operateSql.js'
import _ from 'lodash'
const TABLE1 = 'activity_master.activity'
const TABLE2 = 'activity_master.users'

router.get('/detail/:id',(req,res,next) => {
  if (!+req.params.id) {
    next('参数错误')
  }
  const sql = detailSql(TABLE1,{id:req.params.id})
  try {
    getResult(sql).then((result) => {
      
      res.send(req.app.locals.success(result,'ok'))
    })
  } catch (error) {
    res.send(req.app.locals.error(error))
  }
})
router.delete('/delete',(req,res,next) => {
  const sql = deleteSql(TABLE1,req.body)
  try {
    getResult(sql).then((result) => {
      res.send(req.app.locals.success(result,'ok'))
    })
  } catch (error) {
    res.send(req.app.locals.error(error))
  }
})

// router.get('/list1',hasLogin,getAccount,(req,res,next) => {
//   const sql = listSql(TABLE1, Object.assign({},req.query))
//   // 当前访问用户的信息
//   let { master = {} } = req

//   master = _.omit(master,['openid','secret_str','session_key'])
  
//   try {
//     getResult(sql).then((result) => {
//       result = result.map(e => {
//         const item = e?.master_id == master?.master_id
//         ? Object.assign(e,{masterFlag: true},{master})
//         : Object.assign(e,{masterFlag: false},{master})
//         return item
//       })
//       res.send(req.app.locals.success(result,'ok'))
//     })
//   } catch (error) {
//     
//     res.send(req.app.locals.error(error))
//   }
// })


// 所有列表
router.get('/all',hasLogin,async(req,res,next) => {
  try {
    const listActivitySql = listSql(TABLE1,req.body)
    const rows = await getResult(listActivitySql)
  
    for (let i = 0; i < rows.length; i++) {
      let user = await getResult(detailSql(TABLE2,{id:rows[i].master_id}))
      user = _.omit(user[0],'openid','password')
      rows[i][TABLE2.split('.')[1]] = user
    }
    res.json(req.app.locals.success(rows))
  } catch (error) {
    res.json(req.app.locals.error(error))
  }
})

// 关联用户的列表
router.get('/list',hasLogin,getAccount,async (req,res,next) => {
  try {
    
    const listActivitySql = listSql(TABLE1,req.body)
    let rows = await getResult(listActivitySql)
  
    for (let i = 0; i < rows.length; i++) {
      let user = await getResult(detailSql(TABLE2,{id:rows[i].master_id}))
      user = _.omit(user[0],'openid','password')
      rows[i][TABLE2.split('.')[1]] = user
    }
    // 筛选出自己发布的以及参与的活动
    rows = rows.filter(e => {
      return e.join_list?.split(',').includes(req.master.id.toString()) || e.master_id == req.master.id
    })
    res.json(req.app.locals.success(rows))
  } catch (error) {
    console.log('error: ', error);
    res.json(req.app.locals.error(error))
  }


  // const sql = await joinSql([TABLE1,TABLE2], Object.assign(
  //   {},
  //   req.query, 
  //   {sort: 'asc' ,orderBy:TABLE1+'.create_time'}),
  //   [`${TABLE1}.master_id`,`${TABLE2}.id`],'=')
  // // 当前访问用户的信息
  // let { master } = req
  //   try {
  //   getResult(sql).then((result) => {
  //     result = result.map(e => {

  //       let item = e.master_id === master?.id
  //       ? Object.assign(e,{masterFlag: true})
  //       : Object.assign(e,{masterFlag: false})
  //       item = _.omit(item,['secret_str','session_key','password'])
  //       return item
  //     })
  //     res.send(req.app.locals.success(result,'ok'))
  //   })
  // } catch (error) {
    
  //   res.send(req.app.locals.error(error))
  // }
})

router.post('/add',hasLogin,getAccount, async (req, res, next) => {
  const { master} = req
  try {

    const sql = addSql(TABLE1, Object.assign({},req.body,{master_id:master.id}))

    
    getResult(sql).then((result) => {
      res.json(req.app.locals.success('提交成功'))
    })
  } catch (error) {
    res.json(req.app.locals.error(error))
  }
})

router.put('/put', (req,res, next) => {
  const sql = putSql(TABLE1, req.body,{id:req.body.id})
  try {
    getResult(sql).then((result) => {
      
      res.send(req.app.locals.success(result,'ok'))
    })
  } catch (error) {
    res.send(req.app.locals.error(error))
  }

})

router.post('/join',hasLogin,getAccount,async (req,res,next) => {
  const { master } = req 
  const { id } = req.body
  const sql1 = detailSql(TABLE1,{id})
  const rows = await getResult(sql1)
  const activity = rows[0] || null
  if (!activity) {
    res.json(req.app.locals.error(null,'未找到活动详情'))
    return
  }

  if ((activity.join_list??"").indexOf(_.toString(master.id)) > -1) {
    res.json(req.app.locals.error(null,'请勿重复添加'))
    return
  }

  activity.join_list = new Set((activity.join_list)?activity.join_list.split(','):'').add(_.toString(master.id))

  if (activity.join_list.size > activity.join_count) {
    res.json(req.app.locals.error(null,'超过活动人数'))
    return
  }
  

  activity.join_list = Array.from(activity.join_list).join()
  
  const sql = putSql(TABLE1,{join_list: activity.join_list},{id})
  
  getResult(sql).then((result) => {
    res.json(req.app.locals.success(null,'提交成功'))
  }).catch((err) => {
    
    res.json(req.app.locals.error(null))
  });

})


export default router